package com.hys;

import java.io.FileOutputStream;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Date;

import sun.security.x509.*;

public class CertificateGenerator {
    public static void main(String[] args) throws Exception {
        // Generate key pair
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        PrivateKey privateKey = keyPair.getPrivate();

        // Generate certificate
        X509CertInfo certInfo = new X509CertInfo();
        X500Name owner = new X500Name("CN=192.168.1.106, O=xinLianHua, L=HaErBin, ST=HeiLongJiang, C=China");
        certInfo.set(X509CertInfo.SUBJECT, owner);
        certInfo.set(X509CertInfo.ISSUER, owner);
        certInfo.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(new BigInteger(64, new java.security.SecureRandom())));
        certInfo.set(X509CertInfo.VALIDITY, new CertificateValidity(new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000), new Date(System.currentTimeMillis() + 365 * 24 * 60 * 60 * 1000)));
        certInfo.set(X509CertInfo.KEY, new CertificateX509Key(keyPair.getPublic()));
        certInfo.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(AlgorithmId.get("SHA256withRSA")));
        certInfo.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));

        X509CertImpl cert = new X509CertImpl(certInfo);
        cert.sign(privateKey, "SHA256withRSA");

        // Save private key and certificate to files
        try (FileOutputStream privateKeyOut = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\192.168.1.106\\private.key");
             FileOutputStream certificateOut = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\192.168.1.106\\certificate.crt")) {
            privateKeyOut.write(privateKey.getEncoded());
            certificateOut.write(cert.getEncoded());
        }

        System.out.println("Private key and certificate generated successfully.");
    }

    private static X509Certificate generateCertificate(KeyPair keyPair) throws Exception {
        // Generate and return the X509Certificate object
        // This is just a placeholder method, you need to implement the certificate generation logic here
        // You can use the Bouncy Castle library to generate the certificate
        // Refer to the Bouncy Castle documentation for more information on generating certificates
        throw new UnsupportedOperationException("Certificate generation logic not implemented");
    }

}
